/**
 * name:xue
 * @:公共配置
 */
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
//提取与压缩css
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
//copy插件
const CopyWebpackPlugin = require('copy-webpack-plugin');


//精灵图配置
const SpritesmithPlugin = require('webpack-spritesmith');
const SpritesmithPlugin2 = require('webpack-spritesmith');

// 生成的雪碧图CSS文件模板自定义，也可以不配置直接使用默认的模板
let templateFunction = function (data) {

    // PC端配置
    let shared = '.ico { diaplay: inline-block; background-image: url(I); background-size: Dpx Hpx; }'
        .replace('I', data.sprites[0].image)
        .replace('D', data.sprites[0].total_width)
        .replace('H', data.sprites[0].total_height);

    let perSprite = data.sprites.map(function (sprite) {
        return '.ico-N { width: Wpx; height: Hpx; background-position: Xpx Ypx; }'
            .replace('N', sprite.name.replace(/_/g, '-'))
            .replace('W', sprite.width)
            .replace('H', sprite.height)
            .replace('X', sprite.offset_x)
            .replace('Y', sprite.offset_y);
    }).join('\n');

    // 移动端配置
    let sharedRem = '.ico { diaplay: inline-block; background-image: url(I); background-size: Drem Hrem; }'
        .replace('I', data.sprites[0].image)
        .replace('D', data.sprites[0].total_width / 100)
        .replace('H', data.sprites[0].total_height / 100);

    let perSpriteRem = data.sprites.map(function (sprite) {
        return '.ico-N { width: Wrem; height: Hrem; background-position: X Yrem; }'
            .replace('N', sprite.name.replace(/_/g, '-'))
            .replace('W', sprite.width / 100)
            .replace('H', sprite.height / 100)
            .replace('X', sprite.offset_x / 100)
            .replace('Y', sprite.offset_y / 100);
    }).join('\n');

    return shared + '\n' + perSprite + '\n\n' + sharedRem + '\n' + perSpriteRem;
};
let templateFunction2 = function (data2) {

    // PC端配置
    let shared = '.ico2 { diaplay: inline-block; background-image: url(I); background-size: Dpx Hpx; }'
        .replace('I', data2.sprites[0].image)
        .replace('D', data2.sprites[0].total_width)
        .replace('H', data2.sprites[0].total_height);

    let perSprite = data2.sprites.map(function (sprite) {
        return '.ico-N { width: Wpx; height: Hpx; background-position: Xpx Ypx; }'
            .replace('N', sprite.name.replace(/_/g, '-'))
            .replace('W', sprite.width)
            .replace('H', sprite.height)
            .replace('X', sprite.offset_x)
            .replace('Y', sprite.offset_y);
    }).join('\n');

    // 移动端配置
    let sharedRem = '.ico2 { diaplay: inline-block; background-image: url(I); background-size: Drem Hrem; }'
        .replace('I', data2.sprites[0].image)
        .replace('D', data2.sprites[0].total_width / 100)
        .replace('H', data2.sprites[0].total_height / 100);

    let perSpriteRem = data2.sprites.map(function (sprite) {
        return '.ico-N { width: Wrem; height: Hrem; background-position: X Yrem; }'
            .replace('N', sprite.name.replace(/_/g, '-'))
            .replace('W', sprite.width / 100)
            .replace('H', sprite.height / 100)
            .replace('X', sprite.offset_x / 100)
            .replace('Y', sprite.offset_y / 100);
    }).join('\n');

    return shared + '\n' + perSprite + '\n\n' + sharedRem + '\n' + perSpriteRem;
};

module.exports = {
    entry: './src/main.js',
    output: {
        filename: "[name].bundle.js",
        path: path.resolve(__dirname,'dist'),
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use:{
                    loader: "babel-loader",
                    options: {
                        cacheDirectory: true // 自动babel缓存
                    }
                },
                include: path.join(__dirname,'src'),
                exclude: /node_modules/,
            },
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader,'css-loader','postcss-loader']
            },
            //处理html中的图片
            {
                test: /\.(htm|html)$/i,
                loader: 'html-withimg-loader',
            },
            //处理图片
            {
                test: /\.(png|svg|jpg|jpeg|gif)$/i,  // 正则匹配图片格式名
                use: [
                    {
                        loader: 'file-loader',  // 使用file-loader
                        options: {
                            outputPath: 'images',  // 设置打包后图片存放的文件夹名称
                            name:'[name].[hash:5].[ext]',
                            esModule:false,
                            publicPath:"./images"
                        },
                    },
                ]
            },
            //处理字体
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/i,
                type: 'asset/resource',
            },
        ]
    },
    plugins: [
        //根据模板生成html
        new HtmlWebpackPlugin({
            title: "Webpack App",
            template: "./src/index.html",
            minify: true,
        }),
        //提取压缩css
        new MiniCssExtractPlugin({
            filename: '[name].css',
            chunkFilename: '[id].css',
        }),
        //精灵图插件配置1
        new SpritesmithPlugin({
            src: {
                cwd: path.resolve(__dirname, './src/image/icon'),            // 图标根路径
                glob: '*.png'                                               // 图标类型
            },
            target: {
                image: path.resolve(__dirname, 'dist/images/sprite.png'),   // 生成雪碧图的名称和路径
                css: [
                    [path.resolve(__dirname, 'dist/css/sprite.css'), {      // 生成CSS文件的名称和路径
                        format: 'function_based_template'                   // 模板配置，注意在customTemplates中配置对应名称的属性名
                    }],
                    [path.resolve(__dirname, 'dist/css/sprite.json'), {     // 生成json文件的名称和路径，想看图片数据的可以配置该项
                        format: 'json_texture'
                    }]
                ]
            },
            customTemplates: {
                'function_based_template': templateFunction                 // 上一项使用到的模板变量
            },
            apiOptions: {
                cssImageRef: '../images/sprite.png'                         // 生成的CSS中引用的雪碧图路径
            },
            spritesmithOptions: {
                algorithm: 'top-down',                                      // 生成的雪碧图图标排列方式
                padding: 1                                                  // 图标的间隔
            }
        }),
        //精灵图插件配置2
        new SpritesmithPlugin2({
            src: {
                cwd: path.resolve(__dirname, './src/image/ico'),            // 图标根路径
                glob: '*.png'                                               // 图标类型
            },
            target: {
                image: path.resolve(__dirname, 'dist/images/sprite2.png'),   // 生成雪碧图的名称和路径
                css: [
                    [path.resolve(__dirname, 'dist/css/sprite2.css'), {      // 生成CSS文件的名称和路径
                        format: 'function_based_template2'                   // 模板配置，注意在customTemplates中配置对应名称的属性名
                    }],
                    [path.resolve(__dirname, 'dist/css/sprite2.json'), {     // 生成json文件的名称和路径，想看图片数据的可以配置该项
                        format: 'json_texture'
                    }]
                ]
            },
            customTemplates: {
                'function_based_template2': templateFunction2                 // 上一项使用到的模板变量
            },
            apiOptions: {
                cssImageRef: '../images/sprite2.png'                         // 生成的CSS中引用的雪碧图路径
            },
            spritesmithOptions: {
                algorithm: 'top-down',                                      // 生成的雪碧图图标排列方式
                padding: 1                                                  // 图标的间隔
            }
        }),
        //copy插件
        new CopyWebpackPlugin({
            patterns:[{
                from: './src/static',
                to: './static',
            }]
        })
    ],
    optimization: {
        minimizer: [
            //分离压缩css
            new CssMinimizerPlugin(),
        ]
    }
}